import util from "@/renderer/util";
import { Message } from "@arco-design/web-react";
import qs from "qs";

console.log(process.env.NODE_ENV)
const baseUrl = process.env.NODE_ENV === 'development' ? 'http://localhost:5000/v1/module' : 'https://secretbase.boynextdoor.gay/api/v1/module';

const trans2Params = (params: Record<string, any>) => {
    if (Object.prototype.toString.call(params) !== '[object Object]') return '';
    const keys = Object.keys(params);
    const len = keys.length;
    return keys.reduce((prev: string, cur: string, index: number) => {
        return `${prev}${cur}=${JSON.stringify(params[cur])}${index !== (len - 1) ? '&' : ''}`;
    }, '?');
};

const postRequest = (apiName: string, headers?: Record<string, string>) => {
    return async (data: any, errorNotify?: () => void) => {
        try {
            const totalHeaders = headers || {};
            const token = window.localStorage.getItem('csrfToken');
            if (token) totalHeaders.token = token;
            const requestResult = await fetch(
                baseUrl + apiName,
                {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json',
                        ...totalHeaders,
                    },
                    body: headers?.['content-type'] ? qs.stringify(data) : JSON.stringify(data),
                }
            );
            const resp: ResponseData = await requestResult.json();

            if (resp.ResponseMetadata.Error?.Code === 406) afterTokenOvertime();
            if (!resp.ResponseMetadata.Error) return resp.Result;
        } catch {}
        errorNotify ?  errorNotify() : Message.error(`${apiName} called error.`);
    }
};

const getRequest = (apiName: string, headers?: Record<string, string>) => {
    return async (params: Record<string, any>, errorNotify?: () => void) => {
        try {
            const totalHeaders = headers || {};
            const token = window.localStorage.getItem('csrfToken');
            if (token) totalHeaders.token = token;
            const requestResult = await fetch(
                baseUrl + apiName + trans2Params(params),
                {
                    method: 'GET',
                    headers: {
                        'content-type': 'application/json',
                        ...totalHeaders,
                    },
                }
            );
            const resp: ResponseData = await requestResult.json();
            
            if (resp.ResponseMetadata.Error?.Code === 406) afterTokenOvertime();
            if (!resp.ResponseMetadata.Error) return resp.Result;
        } catch {}
        errorNotify ?  errorNotify() : Message.error(`${apiName} called error.`);
    }
};

export const afterTokenOvertime = () => {
    util.remove('csrfToken');
    util.remove('couple_id');
    util.remove('tag');
    util.remove('state');
    window.location.pathname = '';
}

export {
    postRequest,
    getRequest,
}